package com.by.log.example;

import com.by.log.LoggerFactory;
import com.by.log.Logger;
import com.by.log.filter.DistributedTraceFilter;

import java.util.HashMap;
import java.util.Map;

/**
 * 分布式日志使用示例
 * 展示如何在分布式系统中使用日志框架进行追踪
 */
public class DistributedLoggingExample {
    private static final Logger log = LoggerFactory.getLogger(DistributedLoggingExample.class);
    
    public static void main(String[] args) {
        try {
            System.out.println("开始分布式日志追踪示例...");
            // 模拟服务A调用服务B的场景
            serviceAProcess();
            System.out.println("分布式日志追踪示例完成。");
        } finally {
            System.out.println("关闭日志框架...");
            // 关闭日志框架，释放资源
            LoggerFactory.shutdown();
            System.out.println("日志框架已关闭。");
        }
    }
    
    /**
     * 服务A处理请求
     */
    private static void serviceAProcess() {
        System.out.println("=== Service A Processing ===");
        
        // 开始处理请求，启动一个新的追踪
        Map<String, String> headers = new HashMap<>();
        DistributedTraceFilter.beforeInvoke(headers, "ServiceA", "processRequest");
        
        log.info("Service A started processing request");
        
        try {
            // 模拟业务逻辑
            Thread.sleep(100);
            
            // 调用服务B
            serviceBProcess();
            
            // 记录方法调用统计
            log.recordMethodCall(true, 200);
            
            log.info("Service A completed request successfully");
        } catch (Exception e) {
            log.error(e, "Service A failed to process request");
            log.recordMethodCall(false, 200);
        } finally {
            // 清理追踪上下文
            DistributedTraceFilter.afterInvoke();
        }
    }
    
    /**
     * 服务B处理请求
     */
    private static void serviceBProcess() {
        System.out.println("=== Service B Processing ===");
        
        // 模拟RPC调用，传递追踪信息
        Map<String, String> headers = DistributedTraceFilter.getCurrentContextHeaders();
        DistributedTraceFilter.beforeInvoke(headers, "ServiceB", "handleRequest");
        
        log.info("Service B started processing request");
        
        try {
            // 模拟业务逻辑
            Thread.sleep(50);
            
            // 记录方法调用统计
            log.recordMethodCall(true, 50);
            
            log.info("Service B completed request successfully");
        } catch (Exception e) {
            log.error(e, "Service B failed to process request");
            log.recordMethodCall(false, 50);
        } finally {
            // 清理追踪上下文
            DistributedTraceFilter.afterInvoke();
        }
    }
}